<template>
  <div class="app-container">
    <div v-show="tab_view==1" class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" size="small">
        <el-form-item>
          <el-date-picker
            style="width:240px"
            v-model="pickerDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            :clearable="false"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">类型：</span>
          <el-select v-model="formInline.type" style="width:100px" @change="searchTypeChange">
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">发放对象：</span>
          <el-select v-model="use" multiple collapse-tags style="width:150px">
            <el-option v-for="item in use_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">任务状态：</span>
          <el-select v-model="status" multiple collapse-tags style="width:140px">
            <el-option
              v-for="item in status_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">发放状态：</span>
          <el-select v-model="send_type" multiple collapse-tags style="width:140px">
            <el-option
              v-for="item in send_type_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.name"
            placeholder="请输入名称"
            style="width:150px;"
            clearable
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick" />
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">新建发放</el-button>
      </el-form>
      <el-table
        highlight-current-row
        :data="list"
        border
        size="mini"
        @sort-change="tableSort"
        v-loading.body="listLoading"
      >
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="name"></el-table-column>
        <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
        <el-table-column align="center" label="发放对象" prop="use_name"></el-table-column>
        <el-table-column align="center" label="触发方式" prop="touch_name"></el-table-column>
        <el-table-column align="center" label="任务状态" prop="status_name"></el-table-column>
        <el-table-column align="center" label="发放状态" prop="send_name"></el-table-column>
        <el-table-column align="center" label="发放/领取时间" prop="time"></el-table-column>
        <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
        <el-table-column align="center" label="操作" width="330">
          <template slot-scope="scope">
            <el-button
              v-show="scope.row.type == 2&&scope.row.status >= 2"
              @click="exportClick(scope.row.id,scope.$index)"
              type="primary"
              :loading="scope.row.exportLoading"
              plain
              size="mini"
            >
              导出手机号
              <count-down :ref="'cd'+(scope.$index+(currentPage-1)*20)" />
            </el-button>
            <el-button @click="infoClick(3,scope.row.id)" type="primary" plain size="mini">详情</el-button>
            <el-button
              v-show="(scope.row.type==1&&scope.row.send_type==1)||(scope.row.type==2&&scope.row.status==1)"
              @click="infoClick(2,scope.row.id)"
              type="primary"
              plain
              size="mini"
            >修改</el-button>
            <el-button
              v-show="scope.row.status!=3"
              @click="overClick(scope.row.id)"
              type="danger"
              plain
              size="mini"
            >结束</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="tab_view==2" class="customContainer">
      <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
      <div class="tab_title">{{top_title}}</div>
      <div v-show="isNew">
        <dj-tab :data="step_list" :isNew="isNew" :tab_step="tab_step" @goStep="goStep"></dj-tab>
      </div>
      <div v-show="tab_step==1" class="info">
        <el-form
          :model="infoForm"
          ref="infoForm"
          :rules="rules"
          :disabled="isNew==3||isDisabled"
          label-width="40px"
        >
          <div class="info_optional">
            <div v-if="grant_type.type==1" class="op_title mb_30">
              A类任务
              <span>可根据指定规则实时判断用户是否符合发放标准</span>
            </div>
            <div v-else-if="grant_type.type==2" class="op_title mb_30">
              B类任务
              <span>可基于历史数据按条件筛选既定用户进行发放</span>
            </div>
            <el-form-item label="名称" prop="name">
              <el-input v-model="infoForm.name" :maxlength="20" style="width:90%;" />
            </el-form-item>
            <div style="margin-left:40px" class="grant_remark">发放名称会以标签的形式展现在小程序商品信息中，建议不要超过10个字符</div>
            <div class="op_title">角标（选填）</div>
            <el-form-item label-width="0" prop="corner_mark">
              <el-radio-group v-model="infoForm.corner_mark">
                <el-radio
                  @click.native.prevent="cornerClick(item.id)"
                  v-for="item in corner_list"
                  :label="item.id"
                  :key="item.id"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="op_title">发放对象</div>
            <div class="op_info">{{grant_type.grant_obj_text}}</div>

            <!-- 单笔满赠 -->
            <el-form-item
              style="margin-top:20px"
              v-show="grant_type.id==2"
              label="单笔订单金额满"
              prop="money"
              label-width="110px"
            >
              <el-input v-model="infoForm.money" :maxlength="9" style="width:170px;" />
            </el-form-item>
            <div
              class="grant_remark"
              v-show="grant_type.id==2"
            >单笔订单金额指：用户购买充值、办卡、活动、门票、实物的商品单笔订单应付的金额(不包含优惠券、续期以及发放的商品)</div>

            <!-- 导入用户 -->
            <div class="upload" v-show="isNew!=3&&grant_type.id==3">
              <el-upload
                style="margin-bottom:20px"
                ref="upload"
                action="/"
                accept=".xls, .xlsx"
                :on-change="uploadChange"
                :show-file-list="true"
                :auto-upload="false"
                :limit="1"
                :disabled="beforeUploadLoading"
              >
                <el-button
                  @click="beforeUpload"
                  type="primary"
                  size="small"
                  :loading="beforeUploadLoading"
                >{{user_phone.length||phone_num>=0?"重新导入":"导入用户"}}</el-button>
              </el-upload>
              <div class="download">
                <el-button @click="uploadTemplate" type="primary" size="small">下载模板</el-button>
              </div>
            </div>
            <div v-show="bad_phone_num>0||phone_num>=0" class="upload_info">
              <div v-show="isNew!=3" class="upload_info_title">仅对有效手机号发放</div>
              <div class="upload_info_num">有效手机号：{{phone_num}}个</div>
              <div v-show="bad_phone_num>0" class="upload_info_bad_num">
                无效手机号：{{bad_phone_num}}个
                <el-button
                  @click="uploadPhone"
                  :loading="uploadBadLoading"
                  type="primary"
                  size="small"
                >下载</el-button>
              </div>
              <div  v-show="isNew!=3"
                class="upload_remark"
              >文件上传后对手机号进行筛选，筛选出重复的手机号、格式不对的手机号、不是纯数字的手机号、手机号位数不够的手机号、小程序用户系统里不存在的手机号，视为无效手机号</div>
            </div>

            <!-- 累计满赠 -->
            <el-form-item
              style="margin-top:20px"
              label-width="0"
              v-show="grant_type.id==4"
              prop="history_date"
            >
              <el-date-picker
                style="width:240px"
                size="small"
                v-model="infoForm.history_date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="-"
                :clearable="false"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="historyOptions"
              ></el-date-picker>
              <span style="margin:0 20px 0 10px">期间内</span>
              <span class="grant_remark">请选择历史日期，最多可选最近6个月。开始日期不早于2020-08-03</span>
            </el-form-item>
            <div class="total_money">
              <el-form-item
                v-show="grant_type.id==4"
                label="累计购买金额满"
                prop="between_money_one"
                label-width="110px"
              >
                <el-input
                  size="small"
                  v-model="infoForm.between_money_one"
                  :maxlength="9"
                  style="width:170px;"
                />
              </el-form-item>
              <el-form-item
                v-show="grant_type.id==4"
                prop="between_money_two"
                label="——"
                label-width="50px"
              >
                <el-input
                  size="small"
                  v-model="infoForm.between_money_two"
                  :maxlength="9"
                  style="width:170px;"
                />
              </el-form-item>
            </div>
            <div
              class="grant_remark"
              v-show="grant_type.id==4"
            >累计购买金额指：用户购买充值、办卡、活动、门票、实物的商品累计应付的金额(不包含优惠券、续期以及发放的商品)</div>

            <div class="op_title">触发方式</div>
            <div class="op_info mb_100">{{grant_type.trigger_text}}</div>
          </div>
        </el-form>
      </div>
      <div v-show="tab_step==2" class="info goods">
        <div class="info_optional">
          <div v-if="grant_type.type==1" class="op_title">A类任务</div>
          <div v-else-if="grant_type.type==2" class="op_title">B类任务</div>
          <div v-if="grant_type.id==2" class="op_info">当前发放对象为“单笔满赠”可选择最多1份商品/券一起发放</div>
          <div v-else-if="grant_type.type==2" class="op_info">当前为“B类任务”最多可发放1份商品/券</div>
          <div v-else class="op_info">当前为“A类任务”最多可发放3份商品/券</div>
          <div class="op_title">已选择</div>
          <el-table
            class="goods_table"
            highlight-current-row
            :data="choose_goods_list"
            border
            size="mini"
          >
            <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
            <el-table-column align="center" label="有效期" prop="time"></el-table-column>
            <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
            <el-table-column align="center" label="操作" width="100" v-if="isNew<3" key="set">
              <template slot-scope="scope">
                <el-button
                  :disabled="isDisabled"
                  @click="delCheck(scope.$index)"
                  type="danger"
                  size="mini"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="op_title">选择商品/券</div>
          <div
            style="margin-bottom:20px"
            v-if="grant_type.type==1&&grant_type.use_type==2"
            class="op_info"
          >当发放对象为“单笔满赠”只可选择优惠券、实物类商品、企划类商品进行发放</div>
          <el-form :inline="true" :model="goodsForm" ref="goodsForm" size="small">
            <el-form-item prop="type">
              <el-select
                @change="chooseTypeChange"
                v-model="goodsForm.sell_type"
                style="width:130px"
              >
                <el-option
                  v-for="item in add_type_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="type">
              <span style="color: #888;">类型：</span>
              <el-select v-model="goodsForm.type" style="width:130px">
                <el-option
                  v-for="item in choose_type_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="name">
              <el-input
                v-model="goodsForm.name"
                placeholder="请输入商品名称"
                @keyup.enter.native="goodsSearchClick"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <dj-button size="small" @search="goodsSearchClick">
                <template #default>搜索</template>
              </dj-button>
            </el-form-item>
          </el-form>
          <el-table
            class="goods_table"
            highlight-current-row
            :data="all_goods_list"
            height="400px"
            border
            size="mini"
            v-loading.body="listLoading"
          >
            <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
            <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
            <el-table-column align="center" label="有效期" prop="time"></el-table-column>
            <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
            <el-table-column align="center" label="操作" width="100" v-if="isNew<3" key="set">
              <template slot-scope="scope">
                <el-button
                  :disabled="isDisabled"
                  @click="addCheck(scope.row)"
                  type="primary"
                  size="mini"
                >添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            @current-change="goodsCurrentChange"
            :current-page.sync="goodsPage"
            :page-size="20"
            layout="prev, pager, next, jumper"
            :page-count="goodsTotal"
          ></el-pagination>
        </div>
      </div>
      <div v-show="tab_step==3" class="info">
        <div class="info_optional">
          <div v-if="grant_type.type==1" class="op_title">A类任务</div>
          <div v-else class="op_title">B类任务</div>
          <div
            v-if="grant_type.type==1"
            class="op_info"
          >任务创建后，立即生效，用户在“发放/领取日期”内打开小程序可触发规则判断，符合发放规则的用户可领取或购买</div>
          <div v-else class="op_info">任务创建后，次日08:00:00生效。在“发放/领取日期”内登录小程序，符合条件的用户可领取或购买</div>
          <div class="op_title">发放/领取时间</div>
          <el-form :model="timeForm" ref="timeForm" size="small">
            <el-form-item label="名称" prop="pickerTime">
              <el-date-picker
                :disabled="isDisabled"
                style="width:240px;margin-right:10px"
                v-model="timeForm.pickerTime"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="-"
                :clearable="false"
                size="small"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerTimeForm"
              ></el-date-picker>
              <span>发放/领取时间指开始日期的任务生效的时间至结束日期的23:59:59。结束时间小于30天显示天数，小于72小时显示倒计时。</span>
            </el-form-item>
          </el-form>
          <div class="op_title">限领数量</div>
          <div v-if="grant_type.type==1&&grant_type.use_type==2" class="op_info mb_100">单个用户单笔订单限领1份</div>
          <div v-else class="op_info mb_100">单个用户1个商品/券限领1份</div>
        </div>
      </div>
      <div style="text-align:right;margin-bottom:20px">
        <el-button v-show="tab_step>1&&isNew==1" @click="tab_step--" plain size="small">上一步</el-button>
        <el-button v-show="tab_step<3&&isNew==1" @click="goNext" type="primary" size="small">下一步</el-button>
        <el-button
          v-show="tab_step==3&&isNew==1"
          @click="saveClick"
          type="primary"
          size="small"
        >创建任务</el-button>
        <el-button
          v-show="isDisabled&&isNew==2"
          @click="editClick(3)"
          type="primary"
          size="small"
        >修改</el-button>
        <el-button v-show="!isDisabled&&isNew==2" @click="editClick(1)" plain size="small">取消</el-button>
        <el-button
          v-show="!isDisabled&&isNew==2"
          @click="editClick(2)"
          type="primary"
          size="small"
        >保存</el-button>
      </div>
    </div>
    <!-- 弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="新建发放任务"
      :visible.sync="addTypeDialog"
      width="500px"
    >
      <div class="add_type_top">请先按类型选择发放对象</div>
      <div class="add_type_title">A类发放任务（立即生效）</div>
      <div class="add_type">
        <div
          v-for="(item,i) of grant_type_a"
          :key="i"
          @click="getTypeClick(item.id)"
          class="add_type_info"
          :class="{active:grant_type.type==item.type&&grant_type.use_type==item.use_type}"
        >{{item.name}}</div>
      </div>
      <div class="add_type_title">B类发放任务（次日生效）</div>
      <div class="add_type">
        <div
          v-for="(item,i) of grant_type_b"
          :key="i"
          @click="getTypeClick(item.id)"
          class="add_type_info"
          :class="{active:grant_type.type==item.type&&grant_type.use_type==item.use_type}"
        >{{item.name}}</div>
      </div>
      <div class="add_type_text">{{grant_type.type_text}}</div>
      <div class="add_type_foot">
        <el-button @click="addClick" type="primary">确定</el-button>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div v-show="tab_view==1" class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import {
  getList,
  getPage,
  getGoodsList,
  getGoodsPage,
  grantCreate,
  grantOver,
  grantInfo,
  grantEdit,
  canNew,
  importPhone,
  getExport,
} from "@/api/operation/grantManagement";
import {
  pickerOptionsF,
  pickerDateOneMonth,
  pickerOptionsGtDay,
  pickerDateDot,
  optionMaxTime,
  getGoodsType,
} from "@/utils";
import { commonCharName, money0tox, mobile } from "@/utils/validate";
import { djTab } from "@/components/tab";
import XLSX from "xlsx";
export default {
  components: {
    "dj-tab": djTab,
  },
  data() {
    const vName = (rule, value, callback) => {
      if (this.isNew != 3) {
        if (!value) {
          callback(new Error("请输入名称"));
        } else if (value.length < 2) {
          callback(new Error("请输入2-20位字符"));
        } else {
          if (!commonCharName(value)) {
            callback(new Error("名称不能包含特殊字符"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    const vMoney = (rule, value, callback) => {
      this.checkMOney(rule, value, callback, 2);
    };
    const vMoney1 = (rule, value, callback) => {
      this.checkMOney(rule, value, callback, 4);
    };
    const vMoney2 = (rule, value, callback) => {
      this.checkMOney(rule, value, callback, 4, 1);
    };
    const vWeekDay = (rule, value, callback) => {
      if (this.isNew != 3 && (this.timeForm.week || this.grant_type.id == 4)) {
        if (value.length === 0) {
          callback(new Error("请选择日期"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      list: null,
      listLoading: false,
      addTypeDialog: false,
      beforeUploadLoading: false,
      uploadBadLoading: false,
      isNew: 1, //1 新增 2 修改 3 详情
      isDisabled: false, //是否可修改
      tab_view: 1,
      tab_step: 1,
      top_title: "新建发放任务",
      currentPage: 1,
      totalDataNumber: 0,
      add_type: "",
      add_use: "",
      type_text: "",
      grant_obj_text: "",
      use: ["0", "1", "2", "3", "4"], //发放对象
      status: ["1", "2", "3"], //任务状态
      send_type: ["1", "2"], //发放状态
      use_list: [],
      type_list: [
        { id: "0", name: "全部" },
        { id: "1", name: "A类任务" },
        { id: "2", name: "B类任务" },
      ],
      corner_list: [
        //角标
        { id: "1", name: "新人专享" },
        { id: "2", name: "限时免费" },
      ],
      status_list: [
        { id: "1", name: "未生效" },
        { id: "2", name: "已生效" },
        { id: "3", name: "已结束" },
      ],
      send_type_list: [
        { id: "1", name: "未开始" },
        { id: "2", name: "已开始" },
        { id: "3", name: "已结束" },
      ],
      grant_type_list: [
        //全部发放类型
        {
          id: "0",
          name: "全部用户",
          type: 1,
          use_type: "0",
          type_text:
            "指全部小程序用户。用户登录时判断，满足触发条件时自动发放给用户",
          grant_obj_text: "全部用户：指系统内全部的小程序用户",
          trigger_text: "触发方式：登录/注册。最多同时支持10个已生效的发放任务",
        },
        {
          id: "1",
          name: "新用户",
          type: 1,
          use_type: "1",
          type_text:
            "“新用户”的发放任务同时只能创建1个,结束任务后可再次创建。指未领取/购买过“新用户”发放任务的用户，已领取/购买过的用户则不再发放",
          grant_obj_text: "新用户：指未领取/购买过“新用户”发放任务的用户",
          trigger_text: "触发方式：登录/注册。最多同时支持10个已生效的发放任务",
        },
        {
          id: "2",
          name: "单笔满赠",
          type: 1,
          use_type: "2",
          type_text:
            "根据用户完成购买操作后，单笔订单的应付金额是否满足触发条件来判断是否发放商品/券",
          grant_obj_text:
            "单笔满赠：根据用户完成购买操作后，单笔订单的应付金额是否满足触发条件来判断是否发放商品/券",
          trigger_text: "触发方式：单笔购买。最多同时支持10个已生效的发放任务",
        },
        {
          id: "3",
          name: "导入用户",
          type: 2,
          use_type: "3",
          type_text: "根据上传文件批量导入手机号，最多导入手机号50000个",
          grant_obj_text:
            "导入用户：根据上传文件批量导入用户手机号，文件格式支持：xls、xlxs，可导入手机号数量1~50000",
          trigger_text: "触发方式：登录/注册。每天最多支持5个未生效的发放任务次日凌晨同时筛选用户",
          // trigger_text: "触发方式：用户登录。每天最多支持5个未生效的发放任务次日凌晨同时筛选用户",
        },
        {
          id: "4",
          name: "累计满赠",
          type: 2,
          use_type: "4",
          type_text:
            "根据历史所选时间段内，用户累计应付金额是否满足条件，来筛选用户进行统一发放",
          grant_obj_text:
            "累计满赠：根据历史数据，一段时间内用户在小程序的应付金额来筛选用户",
          trigger_text: "触发方式：登录/注册。每天最多支持5个未生效的发放任务次日凌晨同时筛选用户",
          // trigger_text: "触发方式：用户登录。每天最多支持5个未生效的发放任务次日凌晨同时筛选用户",
        },
      ],
      grant_type_a: [], //A类任务发放类型
      grant_type_b: [], //B类任务发放类型
      grant_type: {},
      step_list: ["1. 基础信息", "2. 选择商品/券", "3. 发放/领取"],
      formInline: {
        start_time: "",
        end_time: "",
        type: "0",
        status: [],
        use: [],
        send_type: [],
        name: "",
      },
      infoForm: {
        type: "",
        use_type: "",
        name: "",
        money: "",
        corner_mark: "",
        start_time: "",
        end_time: "",
        between_money_one: "",
        between_money_two: "",
        history_date: [],
        key: "", // 有效手机号的key
      },
      id: "", //查看的券id
      choose_goods_list: [], //已选商品列表
      all_goods_list: [], //可选商品列表
      user_phone: [], //导入手机号
      user_bad_phone: [], //不符合手机号
      phone_num: -1, //有效手机号数量
      bad_phone_num: 0, //无效手机号数量
      goodsPage: 1,
      goodsTotal: 0,
      goodsForm: {
        //商品搜索
        sell_type: "1",
        type: "0",
        name: "",
      },
      add_type_list: [
        { id: "1", name: "优惠券" },
        { id: "2", name: "商品" },
      ],
      choose_type_list: [],
      goods_type_list: [
        { id: "0", name: "全部" },
        { id: "2", name: "办卡" },
        { id: "3", name: "充值" },
        { id: "4", name: "续期" },
        { id: "5", name: "门票" },
        { id: "6", name: "企划" },
        { id: "7", name: "实物" },
      ],
      con_type_list: [
        { id: "0", name: "全部" },
        { id: "1", name: "代金券" },
      ],
      timeForm: {
        //使用限制
        pickerTime: pickerDateDot(),
      },
      oldInfoData: {}, //修改前的数据
      oldGoodsData: [],
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateOneMonth(),
      pickerTimeForm: pickerOptionsGtDay(),
      historyOptions: {
        disabledDate(time) {
          return (
            time.getTime() > Date.now() ||
            time.getTime() < new Date("2020-08-02") ||
            time.getTime() + 8.64e7 * 186 < Date.now()
          );
        },
      },
      rules: {
        name: [{ required: false, validator: vName, trigger: "blur" }],
        money: [{ required: false, validator: vMoney, trigger: "blur" }],
        between_money_one: [
          { required: false, validator: vMoney1, trigger: "blur" },
        ],
        between_money_two: [
          { required: false, validator: vMoney2, trigger: "blur" },
        ],
        pickerTime: [
          { required: false, validator: vWeekDay, trigger: "change" },
        ],
        history_date: [
          { required: false, validator: vWeekDay, trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.grant_type_a = this.grant_type_list.filter((val) => val.type == 1);
    this.grant_type_b = this.grant_type_list.filter((val) => val.type == 2);
    this.searchTypeChange(0);
    this.searchClick();
  },
  methods: {
    //筛选任务类型切换
    searchTypeChange(type) {
      this.use = [];
      if (type == 0) {
        this.use_list = this.grant_type_list;
        this.use = ["0", "1", "2", "3", "4"];
      } else {
        this.use_list = this.grant_type_list.filter((val) => {
          if (val.type == type) {
            this.use.push(val.id);
          }
          return val.type == type;
        });
      }
    },
    //金额验证
    checkMOney(rule, value, callback, id, money = 0) {
      if (this.grant_type.id == id) {
        if (value === "") {
          return callback(new Error("请输入金额"));
        } else {
          if (money0tox(value, 6) && value / 1 >= money) {
            let money_one = this.infoForm.between_money_one,
              money_two = this.infoForm.between_money_two;
            if (money_one && money_two && money_one / 1 > money_two / 1) {
              this.infoForm.between_money_one = money_two;
              this.infoForm.between_money_two = money_one;
            }
            return callback();
          } else {
            return callback(new Error(`金额只能为${money}.00-999999.99之间`));
          }
        }
      } else {
        return callback();
      }
    },
    // 搜索
    searchClick() {
      optionMaxTime(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start_time = this.pickerDate ? this.pickerDate[0] : "";
        this.formInline.end_time = this.pickerDate ? this.pickerDate[1] : "";
        this.formInline.status = this.status;
        this.formInline.use = this.use;
        this.formInline.send_type = this.send_type;
        this.fetchData();
      });
    },
    // 更新时间排序
    tableSort({ column, prop, order }) {
      this.formInline.sort_by = order === "descending" ? "desc" : "asc";
      this.searchClick();
    },
    getData(data) {
      data.forEach((val) => {
        val.exportLoading = false;
        val.type_name = val.type == 1 ? "A类任务" : "B类任务";
        val.use_name = this.grant_type_list.find(
          (item) => item.use_type == val.use_type
        ).name;
        val.touch_name = val.touch_type == 1 ? "注册/登录" : "单笔购买";
        val.status_name =
          val.status == 1
            ? "未生效"
            : val.status == 2
            ? "已生效"
            : val.status == 3
            ? "已结束"
            : "";
        val.send_name =
          val.send_type == 1
            ? "未开始"
            : val.send_type == 2
            ? "已开始"
            : "已结束";
        val.time =
          val.start_time.split(" ")[0].replace(/-/g, ".") +
          "-" +
          val.end_time.split(" ")[0].replace(/-/g, ".");
      });
      this.list = data;
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.list = [];
      getPage(this.formInline)
        .then((response) => {
          this.totalDataNumber = response.data.page / 1;
          if (this.totalDataNumber == 0) {
            this.listLoading = false;
          } else {
            getList(this.formInline)
              .then((res) => {
                this.listLoading = false;
                this.getData(res.data);
              })
              .catch((res) => {
                this.listLoading = false;
              });
          }
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    handleCurrentChange(val) {
      getList(this.formInline, val)
        .then((res) => {
          this.listLoading = false;
          this.getData(res.data);
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    overClick(id) {
      this.$confirm(
        "结束当前发放任务后不可恢复，请慎重操作，是否确定结束？",
        "提示",
        { type: "warning" }
      ).then(() => {
        grantOver({ id, status: 3 }).then((res) => {
          if (res.code == 1) {
            this.$message.success(res.message);
            this.searchClick();
          }
        });
      });
    },
    // 新增发放任务选择弹窗
    addTypeClick() {
      this.addTypeDialog = true;
      this.grant_type = {};
    },
    backClick() {
      if (this.isNew < 3 && !this.isDisabled) {
        this.$confirm(
          "返回后已修改的数据不会保存，是否放弃本次操作？",
          "提示",
          { type: "warning" }
        ).then(() => {
          this.goBack();
        });
      } else {
        this.goBack();
      }
    },
    goBack() {
      this.$refs.infoForm.resetFields();
      this.$refs.upload.clearFiles();
      this.user_phone = [];
      this.user_bad_phone = [];
      this.phone_num = -1;
      this.bad_phone_num = 0;
      this.infoForm.key = "";
      this.choose_goods_list = [];
      this.$refs.timeForm.resetFields();
      this.goodsForm.sell_type = "1";
      this.goodsForm.name = "";
      this.chooseTypeChange(1);
      this.tab_view = 1;
      this.id = "";
      this.searchClick();
    },
    getTypeClick(id) {
      this.grant_type = this.grant_type_list[id];
    },
    addClick() {
      this.top_title = "新建发放任务";
      this.goodsSearchClick();
      this.infoForm.use_type = this.grant_type.use_type;
      this.infoForm.type = this.grant_type.type;
      if (this.grant_type.type) {
        if (this.grant_type.use_type == 1) {
          canNew({}).then((res) => {
            if (res.code == 1 && res.data.count > 0) {
              this.$message.error(
                "“新用户”的发放任务同时只能创建1个,结束任务后可再次创建。"
              );
            } else {
              this.addTypeDialog = false;
              this.isDisabled = false;
              this.isNew = 1;
              this.tab_view = 2;
              this.tab_step = 1;
            }
          });
        } else {
          this.addTypeDialog = false;
          this.isDisabled = false;
          this.isNew = 1;
          this.tab_view = 2;
          this.tab_step = 1;
        }
      } else {
        this.$message.info("暂不支持");
      }
    },
    // i 3详情  2修改
    infoClick(i, id) {
      this.isNew = i;
      this.top_title = i == 2 ? "修改发放任务" : "发放任务详情";
      this.tab_view = 2;
      this.tab_step = 1;
      this.isDisabled = true;
      this.goodsSearchClick();
      grantInfo({ id }).then((res) => {
        if (res.code == 1) {
          let data = res.data;
          this.id = data.id;
          this.grant_type = this.grant_type_list.filter(
            (val) => val.type == data.type && val.use_type == data.use_type
          )[0];
          data.money = data.money ? (data.money / 100).toFixed(2) : "";
          data.start_time = data.start_time.split(" ")[0];
          data.end_time = data.end_time.split(" ")[0];
          data.between_money_one = (data.between_money_one / 1).toFixed(2);
          data.between_money_two = (data.between_money_two / 1).toFixed(2);
          data.history_date = data.between_time
            ? data.between_time.split(",")
            : [];
          for (let infoKey in this.infoForm) {
            this.infoForm[infoKey] = data[infoKey]
              ? data[infoKey]
              : this.infoForm[infoKey];
          }
          this.oldInfoData = JSON.parse(JSON.stringify(this.infoForm));
          let goods_id = "";
          data.goods_list &&
            data.goods_list.forEach((val) => {
              val.id = val.goods_id;
              goods_id += val.goods_id + ",";
            });
          this.old_goods_id = goods_id.substr(0, goods_id.length - 1);
          this.choose_goods_list = data.goods_list
            ? this.getGoodsData(data.goods_list)
            : [];
          this.oldGoodsData = JSON.parse(
            JSON.stringify(this.choose_goods_list)
          );
          this.timeForm.pickerTime = [data.start_time, data.end_time];
          this.phone_num=data.valid_num?data.valid_num:0;
        }
      });
    },
    verify() {
      if (this.tab_view == 1) {
        return;
      }
      let isPass = false;
      if (this.tab_step == 1) {
        this.$refs.infoForm.validate((valid) => {
          if (this.grant_type.id == 3 && !this.infoForm.key&&this.phone_num<=0) {
            isPass = false;
            this.$message.error("请导入有效手机号");
          } else {
            isPass = valid;
          }
        });
      } else if (this.tab_step == 2) {
        if (this.choose_goods_list.length == 0) {
          this.$message.error("请添加发放的商品/券");
          isPass = false;
        } else {
          isPass = true;
        }
      } else if (this.tab_step == 3) {
        this.$refs.timeForm.validate((valid) => {
          isPass = valid;
        });
      }
      return isPass;
    },
    goNext() {
      if (!this.verify()) {
        return;
      }
      this.tab_step++;
      if (this.tab_step == 2) {
        if (!this.choose_type_list.length) {
          this.choose_type_list =
            this.goodsForm.sell_type == 1
              ? this.con_type_list
              : this.goods_type_list;
        }
      }
    },
    goStep(i) {
      if (this.isNew == 1) {
        return;
      }
      if (!this.isDisabled) {
        this.$confirm(
          "该页面尚未保存，是否要切换页面？切换后修改后的数据不会保存",
          "提示",
          { type: "warning" }
        ).then(() => {
          this.isDisabled = true;
          this.tab_step = i;
        });
      } else {
        this.tab_step = i;
        if (i == 2) {
          if (!this.choose_type_list.length) {
            this.choose_type_list = JSON.parse(
              JSON.stringify(
                this.goodsForm.sell_type == 1
                  ? this.con_type_list
                  : this.goods_type_list
              )
            );
          }
        }
      }
    },
    //  角标
    cornerClick(i) {
      this.infoForm.corner_mark = this.infoForm.corner_mark == i ? "" : i;
    },
    //商品搜索类别切换
    chooseTypeChange(val) {
      this.choose_type_list =
        val == 1
          ? this.con_type_list
          : this.grant_type.type == 1 && this.grant_type.use_type == 2
          ? [this.goods_type_list[5],this.goods_type_list[6]]
          : this.goods_type_list;
      this.goodsForm.type = this.choose_type_list[0].id;
    },
    //商品搜索
    goodsSearchClick() {
      getGoodsPage(this.goodsForm)
        .then((response) => {
          this.goodsTotal = response.data.page / 1;
          if (this.goodsTotal == 0) {
            this.all_goods_list = [];
            this.listLoading = false;
          } else {
            getGoodsList(this.goodsForm)
              .then((res) => {
                this.listLoading = false;
                this.all_goods_list = this.getGoodsData(res.data);
              })
              .catch((res) => {
                this.listLoading = false;
              });
          }
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    getGoodsData(data) {
      data.forEach((val) => {
        val.type_name = getGoodsType(val.type);
        val.time =
          val.chose_time_type == 1
            ? val.effect_time.replace(/-/g, ".").replace(/,/g, "-")
            : val.effect_time > 0
            ? "购买后" + val.effect_time + "天内有效"
            : "";
        val.time = val.time
          ? val.time
          : val.effect_time === "0"
          ? "购买后当天有效"
          : "购买后立即生效";
      });
      return data;
    },
    goodsCurrentChange(val) {
      getGoodsList(this.goodsForm, val)
        .then((res) => {
          this.listLoading = false;
          this.all_goods_list = this.getGoodsData(res.data);
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    // 移除已添加商品
    delCheck(i) {
      this.choose_goods_list.splice(i, 1);
    },
    //添加商品
    addCheck(row) {
      if (this.grant_type.id == 2 && this.choose_goods_list.length >= 1) {
        this.$message.error("“单笔满赠”最多可发放1份商品/券");
        return;
      } else if (
        this.grant_type.type == 2 &&
        this.choose_goods_list.length >= 1
      ) {
        this.$message.error("B类任务最多可发放1份商品/券");
        return;
      }
      if (this.choose_goods_list.length >= 3) {
        this.$message.error("A类任务最多可发放3份商品/券");
        return;
      }
      let canAdd = true;
      for (let val of this.choose_goods_list) {
        if (val.id == row.id) {
          this.$message.error("请勿重复添加");
          canAdd = false;
          break;
        }
      }
      if (canAdd) {
        this.choose_goods_list.push(row);
      }
    },
    getGoodsId() {
      let goods_id = "";
      this.choose_goods_list.forEach((val) => {
        goods_id += val.id + ",";
      });
      return goods_id.substr(0, goods_id.length - 1);
    },
    saveClick() {
      if (!this.verify()) {
        return;
      }
      this.$confirm("确认创建？", "提示", {
        confirmButtonText: "确定创建",
        cancelButtonText: "返回修改",
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: "warning",
      }).then(() => {
        this.save();
      });
    },
    save() {
      // 1
      let data = JSON.parse(JSON.stringify(this.infoForm));
      data.between_time =
        this.grant_type.id == 4 ? data.history_date.join(",") : "";
      delete data.history_date;
      // 2
      data.goods_id = this.getGoodsId();
      // 3
      data.start_time = this.timeForm.pickerTime[0];
      data.end_time = this.timeForm.pickerTime[1];
      grantCreate(data).then((res) => {
        if (res.code == 1) {
          let text =
            data.type == 1
              ? "A类发放任务创建成功，已生效"
              : "B类发放任务创建成功，次日08:00:00生效";
          this.$alert(text, "", {
            confirmButtonText: "确定",
            callback: (action) => {
              this.goBack();
            },
          });
        }
      });
    },
    editClick(i) {
      if (i == 1) {
        this.isDisabled = true;
        if (this.tab_step == 1) {
          this.infoForm = JSON.parse(this.oldInfoData);
        } else if (this.tab_step == 2) {
          this.choose_goods_list = JSON.parse(
            JSON.stringify(this.oldGoodsData)
          );
        } else if (this.tab_step == 3) {
          this.timeForm.pickerTime = [
            this.infoForm.start_time,
            this.infoForm.end_time,
          ];
        }
      } else if (i == 2) {
        if (!this.verify()) {
          return;
        }
        let goods_id = this.getGoodsId();
        this.infoForm.start_time = this.timeForm.pickerTime[0];
        this.infoForm.end_time = this.timeForm.pickerTime[1];
        let data = JSON.parse(JSON.stringify(this.infoForm));
        for (let infoKey in this.oldInfoData) {
          if (this.oldInfoData[infoKey] == data[infoKey]) {
            delete data[infoKey];
          }
        }
        if (
          JSON.stringify(data.history_date) !=
          JSON.stringify(this.oldInfoData.history_date)
        ) {
          data.between_time = data.history_date.join(",");
        }
        delete data.history_date;
        if (goods_id != this.old_goods_id) {
          data.goods_list = [];
          this.choose_goods_list.forEach((val) => {
            let index = this.oldGoodsData.findIndex(
              (item) => item.id == val.id
            );
            if (index == -1) {
              data.goods_list.push({ goods_id: val.id, type: 1 });
            }
          });
          let oldData = JSON.parse(JSON.stringify(this.oldGoodsData));
          this.choose_goods_list.forEach((val) => {
            for (let i in oldData) {
              if (oldData[i].id == val.id) {
                oldData.splice(i, 1);
                break;
              }
            }
          });
          oldData.length &&
            oldData.forEach((val) => {
              data.goods_list.push({ goods_id: val.id, type: 2 });
            });
        }
        if (JSON.stringify(data) === "{}") {
          this.isDisabled = true;
          return;
        }
        data.id = this.id;
        grantEdit(data).then((res) => {
          if (res.code == 1) {
            this.$message.success(res.message);
            this.isDisabled = true;
            this.oldInfoData = JSON.parse(JSON.stringify(this.infoForm));
            this.old_goods_id = goods_id;
            this.oldGoodsData = JSON.parse(
              JSON.stringify(this.choose_goods_list)
            );
          }
        });
      } else {
        this.isDisabled = false;
      }
    },
    beforeUpload() {
      this.$refs.upload.clearFiles();
      this.user_phone = [];
      this.user_bad_phone = [];
      this.phone_num = -1;
      this.bad_phone_num = 0;
      this.infoForm.key = "";
    },
    uploadChange(file) {
      this.beforeUploadLoading = true;
      this.getFile(file.raw)
        .then((res) => {
          this.user_phone = res.code == 1 ? res.batteryArr : [];
          let phone_list = [];
          this.user_phone.sort().forEach((val, i) => {
            if (mobile(val) && val != this.user_phone[i + 1]) {
              phone_list.push(val);
            } else {
              this.user_bad_phone.push(val);
            }
          });
          if (phone_list.length > 0 && phone_list.length <= 50000) {
            return importPhone({ phone_list });
          } else if (phone_list.length > 50000) {
            return { code: -2 };
          } else {
            return { code: -1 };
          }
        })
        .then((res) => {
          if (res.code == 1) {
            this.user_bad_phone.unshift(...res.data.invalid);
            this.bad_phone_num = this.user_bad_phone.length;
            this.phone_num = res.data.valid.length;
            this.infoForm.key = res.data.key;
          } else if (res.code == -1) {
            this.bad_phone_num = this.user_bad_phone.length;
            this.phone_num = 0;
          } else if (res.code == -2) {
            this.$message.error("导入数量超过50000条，请重新操作");
          }
          this.beforeUploadLoading = false;
        });
    },
    getFile(file) {
      let _this = this;
      return new Promise(function (resolve, reject) {
        // 返回Promise对象
        const reader = new FileReader();
        reader.onload = (e) => {
          // 异步执行
          try {
            // 以二进制流方式读取得到整份excel表格对象
            let data = e.target.result,
              workbook = XLSX.read(data, { type: "binary" });
            let batteryArr = [];
            let str = "^" + ["!ref", "!margins", "A1"].join("|") + "$";
            let reg = new RegExp(str);
            for (let item in workbook.SheetNames) {
              let SheetName = workbook.SheetNames[item];
              let sheetInfos = workbook.Sheets[SheetName];
              for (let battery in sheetInfos) {
                if (!reg.test(battery) && sheetInfos[battery].v) {
                  batteryArr.push(sheetInfos[battery].v);
                }
              }
            }
            resolve({ code: 1, batteryArr });
          } catch (e) {
            reject(e.message);
          }
        };
        reader.readAsBinaryString(file);
      });
    },
    //列表导出手机号
    exportClick(welfare_id, index) {
      getExport({ welfare_id });
      this.list[index].exportLoading = true;
      let key = "cd" + (index + (this.currentPage - 1) * 20);
      this.$refs[key].countDownF(60).then(() => {
        this.list[index].exportLoading = false;
      });
    },
    //下载模板
    uploadTemplate() {
      let sheet = [["用户手机号"]];
      this.uploadExcel(sheet, "用户手机号");
    },
    //导出无效手机号
    uploadPhone() {
      this.uploadBadLoading = true;
      setTimeout(() => {
        let sheet = [["无效手机号"]];
        this.user_bad_phone.forEach((val) => {
          sheet.push([val]);
        });
        this.uploadExcel(sheet, "无效手机号");
        this.uploadBadLoading = false;
      }, 0);
    },
    //excel导出
    uploadExcel(sheet, wb_name, wch = 14) {
      //列宽
      let wscols = [{ wch }];

      //生成工作表
      let ws = XLSX.utils.aoa_to_sheet(sheet);

      //生成工作簿
      let wb = XLSX.utils.book_new();

      //设置列宽
      ws["!cols"] = wscols;

      //将工作表添加至工作簿中
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      XLSX.writeFile(wb, `${wb_name}.xlsx`);
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.customContainer {
  overflow-y: auto;
  .grant_remark {
    color: #999;
    font-size: 14px;
  }
}
.info {
  background: #fff;
  padding: 10px 0 10px;
  margin-bottom: 20px;
}
.goods {
  .goods_info {
    margin: 20px 0;
    .title {
      color: #606266;
      margin-bottom: 5px;
    }
  }
  .goods_table {
    margin-bottom: 15px;
  }
  .goods_type {
    margin: 50px 0 180px;
  }
  .store_info {
    margin: 50px 0 180px;
    color: #bbb;
    font-size: 16px;
  }
  .store_choose {
    min-width: 960px;
    margin-bottom: 30px;
  }
  .time_info {
    margin: 20px 0 0 20px;
    .remark {
      color: #606266;
      margin-top: 10px;
    }
    .intime {
      display: flex;
      .intime_item {
        margin: 0 10px;
      }
    }
    .dis_day_text {
      line-height: 25px;
      color: #606266;
    }
  }
  .time_title {
    margin-bottom: 10px;
  }
  .time_item {
    margin-top: 0;
    font-size: 14px;
  }
}
.add_type_top {
  font-size: 18px;
  color: #888;
}
.add_type_title {
  font-size: 16px;
  margin: 20px 0;
}
.add_type_text {
  font-size: 16px;
  margin-top: 20px;
}
.add_type {
  display: flex;
  .add_type_info {
    display: inline-block;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border: 1px solid #ccc;
    cursor: pointer;
  }
  .add_type_info:hover {
    background: #409eff;
    color: #fff;
    border-color: #409eff;
  }
  .add_type_info.active {
    background: #409eff;
    color: #fff;
    border-color: #409eff;
  }
  .add_type_info + .add_type_info {
    margin-left: 80px;
  }
}
.add_type_foot {
  margin-top: 20px;
  text-align: center;
}
.tab_title {
  width: 200px;
  font-size: 20px;
  font-weight: bold;
  margin: 5px 0 20px 70px;
}

.info_optional {
  padding: 0 20px;
  .op_title {
    margin: 30px 0 20px;
    font-size: 16px;
    font-weight: bold;
    color: #282828;
    border-bottom: 1px solid #dcdfe6;
    span {
      font-weight: normal;
      font-size: 14px;
      margin-left: 20px;
    }
  }
  .op_info {
    font-size: 14px;
  }
  .mb_30 {
    margin-bottom: 30px;
  }
  .mb_100 {
    margin-bottom: 100px;
  }
  .total_money {
    display: flex;
    align-items: center;
  }
  .upload {
    display: flex;
    margin-top: 20px;
    position: relative;
    .download {
      position: absolute;
      top: 0;
      left: 120px;
      // margin-left: 20px;
    }
  }
  .upload_info {
    font-size: 14px;
    .upload_info_title {
      font-weight: bold;
    }
    .upload_info_num {
      margin-top: 15px;
    }
    .upload_info_bad_num {
      color: #f56c6c;
    }
    .upload_remark {
      margin-top: 15px;
      color: #999;
    }
  }
}
</style>
